<?php
/**
 * Created by PhpStorm.
 * User: soosoogoo
 * Date: 2018/12/10
 * Time: 11:02 PM
 */

namespace Library\Core;

use Config\Main;
use ZScript\APP;

class Config
{
    public static $config;
    public static $key;

    /**
     * ------------------------------------------------------------------
     * 获取配置信息
     * @return mixed
     * @author soosoogoo
     * ------------------------------------------------------------------
     */
    public static function getConfig($field = false)
    {
        if ($field) {
            return isset(self::$config[$field]) ? self::$config[$field][0] : "";
        }

        return self::$config;
    }

    /**
     * ------------------------------------------------------------------
     * @author soosoogoo
     * ------------------------------------------------------------------
     */
    public static function refreshConfig($config)
    {
        self::$config = $config;
        $key = str_replace("\\", "-", Main::projectName()) . '-Config';
        Links::getMainRedis()->hSet($key, APP::getWorkerId(), json_encode($config));

        \swoole_timer_tick(1000, function () use ($key) {
            //定期更新redis
            $config = Links::getMainRedis()->hGet($key, APP::getWorkerId());
            $config = $config ? json_decode($config, true) : [];

            self::$config = $config;
        });
    }

    /**
     * @desc 获取worker 配置
     * @return array|mixed
     * ------------------------------------------------------------
     */
    public static function getWorkConfig()
    {
        $key = str_replace("\\", "-", Main::projectName());

        //绑定进程，在workstart 调用 防止进程死掉
        $config = Links::getMainRedis()->hGet($key, APP::getWorkerId());

        return $config ? json_decode($config, true) : [];
    }

    /**
     * @desc 删除任务配置
     * ------------------------------------------------------------
     */
    public static function delWorkerConfig()
    {
        $key = str_replace("\\", "-", Main::projectName());

        return Links::getMainRedis()->del($key);
    }

    /**
     * @desc 保存worker 配置
     * @param $workId
     * @param $job
     * @return bool|int
     * ------------------------------------------------------------
     */
    public static function saveWorkConfig($workId, $job)
    {
        $key = str_replace("\\", "-", Main::projectName());
        //绑定进程，在workstart 调用 防止进程死掉
        return Links::getMainRedis()->hSet($key, $workId, json_encode($job));
    }

}